package implementation1.app.commands;

import exceptions.CommandErrorFromUserException;
import exceptions.CommandException;
import exceptions.StreamException;
import implementation1.app.Global;
import implementation1.app.streams.AccessAttributes;
import implementation1.data.states.TerminatedStatus;
import interfaces.app.IProcess;
import interfaces.data.IHandle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * Class for handle of command "ps" for showing of all processes in virtual machine.
 * Created: 22.10.11
 *
 * @author Jan Svab, Jan Kolena
 */
public class Ps extends Command
{
    /**
     * Default constructor.
     *
     * @param parent parent process over which is command processed
     * @param handle parameters of command
     */
    public Ps(IProcess parent, IHandle handle)
    {
        super(parent, handle);
    }

    /**
     * Main method for processing of command.
     *
     * @param args arguments of command
     * @throws CommandException Thrown if occurs error during processing of the command.
     */
    public void mainCommand(String[] args) throws CommandException
    {
        if (handle.getOut() == null)
        {
            throw new CommandException(bundle.getString("error.outputStream.empty"));
        }

        //analyzing of arguments and setting of output

        String ln = String.format("%-8s %-8s %-10s %-18s %-20s", "PID", "PARENT", "NAME", "STATUS", "OWNER");
        try
        {
            handle.getOut().open(AccessAttributes.WRITE);
            openedStreamsOfProcess.add(handle.getOut());

            Collection<IProcess> processes = filterProcesses(this.getRootProcess().getChildrenRecursively(), handle.getParams());

            if (processes.size() == 0)
            {
                throw new CommandErrorFromUserException(bundle.getString("error.ps.NoProcesses"));
            }

            handle.getOut().writeLine(ln);

            for (IProcess process : processes)
            {
                if (Thread.interrupted()) //in other process was created request on terminate this process
                {
                    status = new TerminatedStatus();
                    break;
                }

                if (hasEndStatus()) //thread should quit
                {
                    break;
                }

                int parentPID = (process.getParent() == null) ? 0 : process.getParent().getPid();
                ln = String.format("%-8d %-8d %-10s %-18s %-20s", process.getPid(), parentPID, process.toString(),
                        process.getStatus().getNameOfStatus(), process.getHandle().getAccount().getNick());
                handle.getOut().writeLine(ln);
            }
        } catch (StreamException e)
        {
            throw new CommandException(e.getMessage());
        } finally
        {
            Global.closeStreamQuietly(handle.getOut());
            openedStreamsOfProcess.remove(handle.getOut());
        }
    }

    /**
     * Filters processes according to command arguments.
     *
     * @param processes The processes list.
     * @param arguments The arguments of the command.
     * @return Filtered processes.
     * @throws CommandErrorFromUserException When some error occurs.
     */
    private Collection<IProcess> filterProcesses(Collection<IProcess> processes, String[] arguments) throws CommandErrorFromUserException
    {
        /*
        -A -e aux  All processes
        r   only running
        -U   select by name od user ID
        -p   select by processid
        */

        boolean allProcesses = false;
        boolean selectByPID = false;
        int pid = 0;

        //default - write only my processes
        boolean selectByUser = true;
        String user = handle.getAccount().getNick();

        for (int i = 0; i < arguments.length; i++)
        {
            String arg = arguments[i];
            if (arg.startsWith("-"))
            {
                switch (arg.charAt(1))
                {
                    case 'A':
                    {
                        allProcesses = true;
                    }
                    break;
                    case 'U':
                    {
                        selectByUser = true;
                        if (i == arguments.length - 1 || arguments[++i].startsWith("-"))
                        {
                            throw new CommandErrorFromUserException(bundle.getString("error.ps.NotSpecified.User"));
                        }

                        user = arguments[++i];
                    }
                    break;
                    case 'p':
                    {
                        selectByPID = true;

                        if (i == arguments.length - 1 || arguments[++i].startsWith("-"))
                        {
                            throw new CommandErrorFromUserException(bundle.getString("error.ps.NotSpecified.PID"));
                        }

                        try
                        {
                            pid = Integer.parseInt(arguments[++i]);
                        } catch (NumberFormatException e)
                        {
                            throw new CommandErrorFromUserException(bundle.getString("error.ps.WrongFormatPID"));
                        }
                    }
                    break;

                    default:
                        throw new CommandErrorFromUserException(String.format(bundle.getString("error.arguments.wrongArgument"), arg));
                }
            }
            else
            {
                if (arg.matches("(\\d)*"))
                {
                    try
                    {
                        pid = Integer.parseInt(arg);
                        selectByPID = true;
                    } catch (NumberFormatException e)
                    {
                        throw new CommandErrorFromUserException(bundle.getString("error.ps.WrongFormatPID"));
                    }
                }
                else
                {
                    if (arg.compareTo("aux") == 0)
                    {
                        allProcesses = true;
                    }
                    else
                    {
                        throw new CommandErrorFromUserException(String.format(bundle.getString("error.arguments.wrongArgument"), arg));
                    }
                }
            }
        }

        /* -------------------------------- */

        if (allProcesses) return processes;

        ArrayList<IProcess> plist = new ArrayList<IProcess>();

        Iterator<IProcess> it = processes.iterator();
        while (it.hasNext())
        {
            boolean rem = false;
            IProcess process = it.next();

            if (selectByUser)
            {
                if (process.getHandle().getAccount().getNick().compareTo(user) != 0) rem = true;
            }
            if (selectByPID)
            {
                if (process.getPid() != pid) rem = true;
            }

            if (!rem) plist.add(process);
        }

        return plist;
    }

    @Override
    public String toString()
    {
        return "ps";
    }
}
